#include "TCP_SERVER.hpp"
#include <rtthread.h>
#include <sys/socket.h> /* 使用BSD socket，需要包含socket.h头文件 */
#include <netdb.h>
#include <string.h>
#include <finsh.h>
#include <sys/errno.h>

TCP_SERVER::TCP_SERVER(rt_uint32_t stack_size,
                       rt_uint8_t priority,
                       rt_uint32_t tick,
                       const char *name) : Thread(stack_size, priority, tick, name)
{
    m_recvData = new std::vector<uint8_t>();
    dataReady = false;
    m_state = STATE_MACHINE::EXIT;
}

TCP_SERVER::~TCP_SERVER()
{
    delete m_recvData;
}

TCP_SERVER *TCP_SERVER::getInstance()
{
    static TCP_SERVER instance(2048, 10, 20, "TCP_SERVER_Thread");
    return &instance;
}

void TCP_SERVER::run(void *parameter)
{
    constexpr rt_size_t BUFSZ = 1024;
    constexpr char send_data[] = "This is TCP Server from RT-Thread."; /* 发送用到的数据 */

    char *recv_data; /* 用于接收的指针，后面会做一次动态分配以请求可用内存 */
    socklen_t sin_size;
    int sock, connected, bytes_received;
    struct sockaddr_in server_addr, client_addr;
    rt_bool_t stop = RT_FALSE; /* 停止标志 */
    int ret;

    recv_data = static_cast<char *>(rt_malloc(BUFSZ + 1)); /* 分配接收用的数据缓冲 */
    if (recv_data == RT_NULL)
    {
        rt_kprintf("No memory\n");
        return;
    }

    /* 一个socket在使用前，需要预先创建出来，指定SOCK_STREAM为TCP的socket */
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        /* 创建失败的错误处理 */
        rt_kprintf("Socket error\n");

        /* 释放已分配的接收缓冲 */
        rt_free(recv_data);
        return;
    }

    /* 初始化服务端地址 */
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(5000); /* 服务端工作的端口 */
    server_addr.sin_addr.s_addr = INADDR_ANY;
    rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));

    /* 绑定socket到服务端地址 */
    if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
    {
        /* 绑定失败 */
        rt_kprintf("Unable to bind\n");

        /* 释放已分配的接收缓冲 */
        rt_free(recv_data);
        return;
    }

    /* 在socket上进行监听 */
    if (listen(sock, 5) == -1)
    {
        rt_kprintf("Listen error\n");

        /* release recv buffer */
        rt_free(recv_data);
        return;
    }

    rt_kprintf("\nTCPServer Waiting for client on port 5000...\n");
    while (stop != RT_TRUE)
    {
        sin_size = sizeof(struct sockaddr_in);

        /* 接受一个客户端连接socket的请求，这个函数调用是阻塞式的 */
        connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size);
        /* 返回的是连接成功的socket */
        if (connected < 0)
        {
            rt_kprintf("accept connection failed! errno = %d\n", errno);
            continue;
        }

        /* 接受返回的client_addr指向了客户端的地址信息 */
        rt_kprintf("I got a connection from (%s , %d)\n",
                   inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

        m_state = STATE_MACHINE::IDLE;
        dataReady = false;
        m_recvData->clear();

        /* 客户端连接的处理 */
        while (1)
        {
            /* 发送数据到connected socket */
            ret = send(connected, send_data, strlen(send_data), 0);
            if (ret < 0)
            {
                /* 发送失败，关闭这个连接 */
                closesocket(connected);
                rt_kprintf("\nsend error,close the socket.\r\n");
                break;
            }
            else if (ret == 0)
            {
                /* 打印send函数返回值为0的警告信息 */
                rt_kprintf("\n Send warning,send function return 0.\r\n");
            }

            /* 从connected socket中接收数据，接收buffer是1024大小，但并不一定能够收到1024大小的数据 */
            bytes_received = recv(connected, recv_data, BUFSZ, 0);
            if (bytes_received < 0)
            {
                /* 接收失败，关闭这个connected socket */
                closesocket(connected);
                break;
            }
            else if (bytes_received == 0)
            {
                /* 打印recv函数返回值为0的警告信息 */
                rt_kprintf("\nReceived warning,recv function return 0.\r\n");
                closesocket(connected);
                break;
            }

            /* 有接收到数据，把末端清零 */
            recv_data[bytes_received] = '\0';
            if (strcmp(recv_data, "q") == 0 || strcmp(recv_data, "Q") == 0)
            {
                /* 如果是首字母是q或Q，关闭这个连接 */
                closesocket(connected);
                break;
            }
            else if (strcmp(recv_data, "exit") == 0)
            {
                /* 如果接收的是exit，则关闭整个服务端 */
                closesocket(connected);
                stop = RT_TRUE;
                break;
            }
            else
            {
                processData(recv_data, bytes_received);
            }

            if (m_state == STATE_MACHINE::ERROR_STATE)
            {
                // 若发生错误，则退出循环，需要重新连接客户端
                closesocket(connected);
                break;
            }
        }
    }

    /* 退出服务 */
    closesocket(sock);

    /* 释放接收缓冲 */
    rt_free(recv_data);
}

void TCP_SERVER::processData(const char *recvData, const int bytesReceived)
{
    // get frame head
    TCP_FRAME_HEAD head = static_cast<TCP_FRAME_HEAD>(recvData[0] & 0x0F);

    switch (m_state)
    {
    case STATE_MACHINE::IDLE:
    {
        switch (head)
        {
        case TCP_FRAME_HEAD::Single:
            // 单帧数据，直接处理
            m_recvData->clear();
            for (int i = 1; i < bytesReceived; i++)
            {
                m_recvData->push_back(static_cast<uint8_t>(recvData[i]));
            }
            m_state = STATE_MACHINE::IDLE;
            dataReady = true;
            break;
        case TCP_FRAME_HEAD::First:
            // 第一帧数据，开始接收
            m_recvData->clear();
            for (int i = 1; i < bytesReceived; i++)
            {
                m_recvData->push_back(static_cast<uint8_t>(recvData[i]));
            }
            m_state = STATE_MACHINE::WAIT_NEXT;
            dataReady = false;
            break;
        case TCP_FRAME_HEAD::Middle:
        case TCP_FRAME_HEAD::Last:
        default:
            // 非第一帧数据，忽略
            m_state = STATE_MACHINE::ERROR_STATE;
            dataReady = false;
            m_recvData->clear();
            break;
        }
        break;
    }
    case STATE_MACHINE::WAIT_NEXT:
        switch (head)
        {
        case TCP_FRAME_HEAD::Middle:
            for (int i = 1; i < bytesReceived; i++)
            {
                m_recvData->push_back(static_cast<uint8_t>(recvData[i]));
            }
            m_state = STATE_MACHINE::WAIT_NEXT;
            dataReady = false;
            break;
        case TCP_FRAME_HEAD::Last:
            for (int i = 1; i < bytesReceived; i++)
            {
                m_recvData->push_back(static_cast<uint8_t>(recvData[i]));
            }
            m_state = STATE_MACHINE::IDLE;
            dataReady = true;
            break;
        case TCP_FRAME_HEAD::Single:
        case TCP_FRAME_HEAD::First:
        default:
            // 错误的第一帧数据，忽略
            m_state = STATE_MACHINE::ERROR_STATE;
            dataReady = false;
            m_recvData->clear();
            break;
        }
        break;
    case STATE_MACHINE::EXIT:
    default:
        break;
    }
}

std::vector<uint8_t> *TCP_SERVER::getData()
{
    if (!dataReady)
    {
        return nullptr;
    }
    dataReady = false;
    rt_kprintf("getData!\n");
    return m_recvData;
}
